package com.cherry.androidcode.video

import android.annotation.SuppressLint
import android.util.Log
import com.cherry.androidcode.AppConstant
import com.cherry.androidcode.entity.VideoSearchList
import com.cherry.androidcode.mvp1.MVPBasePresenter
import com.cherry.androidcode.okgo.JsonConvert
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import com.tencent.mmkv.MMKV
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.Response
import org.jsoup.Jsoup

/**
 * @author Cherry(dongmiansheng@gmail.com)
 * @since 2019/8/25
 */

class VideoChildListPresenter : MVPBasePresenter<VideoChildListContract.View>(), VideoChildListContract.Presenter {


    @SuppressLint("CheckResult")
    override fun searchData(keyword: String, page: Int, isRefresh: Boolean) {
//        yiFangSearch(keyword, page, isRefresh)
        OkGo.get<MutableList<VideoSearchList>>(MMKV.defaultMMKV().decodeString(AppConstant.QILING6080_URL) + "/vod/search/page/$page/wd/$keyword.html")
                .headers("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Mobile Safari/537.36")
                .headers("Accept", "text/html,application/xhtml")
                .converter(object : JsonConvert<MutableList<VideoSearchList>>() {
                    override fun convertResponse(response: Response): MutableList<VideoSearchList>? {
                        val document = Jsoup.parse(response.body()?.string())
                        val liElements = document.body().select(".main>.index-area>ul").first().children()
                        return liElements?.map {
                            val aElement = it.selectFirst(".p1>a")

                            val videoLink = aElement.attr("href")
                            val cover = aElement.selectFirst("img.lazy").attr("src")

                            val spanElement = aElement.selectFirst("span.lzbz")
                            val videoName = spanElement.selectFirst("p.name").text()
                            val videoInfoPElement = spanElement.select("p.actor")
                            val actor = videoInfoPElement[0].text()
                            val split = videoInfoPElement[2].text().split("/")
                            val area = split[0]
                            val time = split[1]
                            val otherInfo = aElement.selectFirst("p.other>i").text()

                            VideoSearchList(videoName, videoLink, cover, actor, area, time, otherInfo)
                        }?.toMutableList()
                    }
                })
                .adapt(ObservableBody<MutableList<VideoSearchList>>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    Log.e("search------data", it.joinToString())
                    view?.onLoadData(it, isRefresh)
                }, {
                    it.printStackTrace()
                    view?.onLoadDataError(it.message ?: "", isRefresh)
                })
    }

    @SuppressLint("CheckResult")
    private fun yiFangSearch(keyword: String, page: Int, isRefresh: Boolean) {
        OkGo.get<MutableList<VideoSearchList>>(MMKV.defaultMMKV().decodeString(AppConstant.YIFANG_URL) + "/index.php?m=vod-search")
                .headers("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Mobile Safari/537.36")
                .headers("Accept", "text/html,application/xhtml")
                .params("wd", keyword)
                .params("page", page)//废弃了
                .converter(object : JsonConvert<MutableList<VideoSearchList>>() {
                    override fun convertResponse(response: Response): MutableList<VideoSearchList>? {
                        val document = Jsoup.parse(response.body()?.string())
                        val liElements = document.body().select("div.search>ul.sul>li")
                        return liElements.map {
                            val aElement = it.select("a.link").first()
                            val videoLink = aElement.attr("href")
                            val videoName = aElement.attr("title")
                            val imgElement = aElement.select("div.simg img.lazy")
                            val cover = imgElement.attr("data-original").run {
                                if (startsWith("http://") || startsWith("https://")) {
                                    this
                                } else {
                                    MMKV.defaultMMKV().decodeString(AppConstant.YIFANG_URL).plus(this)
                                }
                            }

                            val spanElements = aElement.select("div.stext span")

                            var actor: String? = null
                            var area: String? = null
                            var time: String? = null
                            //                            run outLoop@{
                            spanElements.forEach { spanChild ->
                                val emHtml = spanChild.select("em")?.first()?.text()

                                emHtml?.takeIf { emText ->
                                    emText.contentEquals("主演：")
                                }?.let {
                                    actor = spanChild.text().substringAfterLast("：")
                                    // 这里return@outLoop 相当于break
                                    //                                        return@outLoop
                                    // 这里return@forEach 相当于continue
                                    return@forEach
                                }
                                emHtml?.takeIf { emText ->
                                    emText.contentEquals("地区/年代：")
                                }?.let {
                                    val split = spanChild.text().substringAfterLast("：").split("/")
                                    area = split[0]
                                    time = split[1]
                                    return@forEach
                                }
                            }
                            //                            }
                            VideoSearchList(videoName, videoLink, cover, actor, area, time)
                        }.toMutableList()
                    }

                })
                .adapt(ObservableBody<MutableList<VideoSearchList>>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    Log.e("search------data", it.joinToString())
                    view?.onLoadData(it, isRefresh)
                }, {
                    it.printStackTrace()
                    view?.onLoadDataError(it.message ?: "", isRefresh)
                })
    }
}